<template>
  <div>
    <el-card shadow="hover" class="layout-padding-auto">
      <div class="sparePart">
        <div class="sparePart__tree">
          <div class="title">设备类型</div>
          <el-input v-model="filterText" placeholder="输入名称搜索" />
          <el-tree
            ref="treeRef"
            :data="data"
            :props="defaultProps"
            @node-click="handleNodeClick"
            default-expand-all
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :indent="10"
          >
            <template #default="{ node, data }">
              <span
                class="custom-tree-node show-hide"
                :class="{ active: currentNode.id == data.id }"
              >
                <span v-if="node.label.length > 8" class="treeLabel">{{
                  node.label
                }}</span>
                <span v-else>{{ node.label }}</span>
              </span>
            </template>
          </el-tree>
        </div>
        <div class="sparePart__table">
          <div style="display: flex; margin-bottom: 15px">
            <h1>
              {{ deviceName }}设备类型关联备件 <span>(共{{ total }}件)</span>
            </h1>
          </div>
          <TableSearch
            :search="state.search"
            @search="onSearch"
            @listenClick="listenClick"
          />
          <Table
            ref="tableRef"
            v-bind="state.tableData"
            class="table-demo"
            @pageChange="onTablePageChange"
            @listenClick="listenClick"
            @dataList="dataList"
          >
            <template #default="{ slotData, slotColumn }">
              <div v-if="slotColumn.key === 'careerType'">
                {{ slotData.careerType == 1 ? '维修' : '维保' }}
              </div>
            </template>
          </Table>
        </div>
      </div>
      <RelevanceDialog
        :relevanceDialog="relevanceDialog"
        :relevanceForm="relevanceForm"
        @relevance="relevance"
        @relevanceSubmit="relevanceSubmit"
      >
      </RelevanceDialog>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { ElMessage, ElTree, ElMessageBox } from 'element-plus'
import { ref, reactive, defineAsyncComponent, watch, onMounted } from 'vue'
import { dictionaryList } from '/@/api/publicApi'
import { removeRelevanceApi } from '/@/api/assets'
import { buttonDisplayOrNot } from '../../utils/buttonBoolean'
import { getButtonListByRoleApi } from '/@/api/publicApi'
import { Session } from '/@/utils/storage'
const menu = Session.get('menu')
const buttonCodes = ref<any>([])
const RelevanceDialog = defineAsyncComponent(
  () => import('./components/RelevanceDialog.vue')
)
const Table = defineAsyncComponent(
  () => import('/@/components/table/index.vue')
)
const TableSearch = defineAsyncComponent(
  () => import('/@/components/table/search.vue')
)
const deviceId = ref('')
const deviceName = ref('')
const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()

interface Tree {
  id: string
  configValue: string
  children?: Tree[]
  customizeFlag: number
  parentId: string
}
const defaultProps = {
  children: 'children',
  label: 'configValue'
}

watch(filterText, (val) => {
  treeRef.value!.filter(val)
})

const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.configValue.includes(value)
}

const data = ref<Tree[]>([])
let currentNode = ref({
  id: '',
  configValue: '',
  children: [],
  customizeFlag: 0,
  parentId: ''
})

const tableRef = ref<RefType>()
const state = reactive<TableDemoState>({
  tableData: {
    flash: false, // 刷新表格
    // 表头内容（必传，注意格式）
    header: [
      { key: 'partNum', colWidth: '', title: '备件编号', type: 'text' },
      { key: 'partName', colWidth: '', title: '备件名称', type: 'text' },
      { key: 'partTypeName', colWidth: '', title: '备件类型', type: 'text' },
      { key: 'realStock', colWidth: '', title: '实际库存', type: 'text' },
      {
        key: 'safeStock',
        colWidth: '',
        title: '最低安全库存',
        type: 'text'
      },
      { key: 'createTime', colWidth: '', title: '关联时间', type: 'text' }
    ],
    columnBtn: [
      {
        name: 'delRelevance',
        text: '删除关联',
        type: 'danger',
        btns: buttonCodes.value,
        btnCode: 'devicePartDeleteBtn'
      }
    ],
    // 配置项（必传）
    config: {
      listApi: '/device/mobile/devicePartRelevance/partRelevanceList',
      listHttp: 'post',
      total: 0, // 列表总数
      loading: true, // loading 加载
      noPage: false, // 是否分页
      isSerialNo: false, // 是否显示表格序号
      isSelection: false, // 是否显示表格多选
      isOperate: true, // 是否显示表格操作栏
      isExtend: false, // 是否可以扩展
      operateWidth: '150', //操作栏宽度
      fixed: 'right' //操作栏固定
    },
    // 搜索参数
    param: {
      deviceType: '' // 必传参数，分页的不要传
    }
  },
  // 搜索表单，动态生成（传空数组时，将不显示搜索，注意格式）
  search: {
    param: [
      {
        label: '',
        prop: 'keyword',
        placeholder: '可输入备件名称/编号搜索',
        type: 'input'
      },
      {
        label: '备件类型',
        prop: 'partType',
        placeholder: '备件类型',
        options: [],
        type: 'select'
      }
    ],
    btn: [
      {
        text: '关联备件',
        fun: 'relevancePart',
        disable: false,
        loading: false,
        type: 'primary',
        hide(): boolean {
          return false
        },
        btns: buttonCodes.value,
        btnCode: 'devicePartAssociatedBtn'
      }
    ],
    reset: true
  }
})

const childArr = ref<any>([])
const handleNodeClick = (data: any) => {
  currentNode.value = data
  deviceId.value = data.id
  deviceName.value = data.configValue
  state.tableData.param.deviceType = data.id
  getTableData()
}

const getDeviceType = () => {
  dictionaryList({ configType: 'device_type', keyword: '' }).then((res) => {
    if (res.code == 0) {
      data.value = res.data
      if (data.value.length) {
        currentNode.value = data.value[0]
        state.tableData.param.deviceType = currentNode.value.id
        deviceId.value = currentNode.value.id
        deviceName.value = currentNode.value.configValue
        getTableData()
      }
    }
  })
}
getDeviceType()

// 初始化列表数据
const getTableData = () => {
  state.tableData.flash = !state.tableData.flash
}
// 搜索点击时表单回调
const onSearch = (data: EmptyObjectType) => {
  state.tableData.param = Object.assign({}, state.tableData.param, { ...data })
  // console.log(state.tableData.param);
  state.tableData.flash = !state.tableData.flash
}
// 分页改变时回调
const onTablePageChange = (page: TableDemoPageType) => {
  state.tableData.param.pageNum = page.pageNum
  state.tableData.param.pageSize = page.pageSize
  getTableData()
}

const total = ref(0)
const dataList = (list: any) => {
  total.value = list.total
}

const getPartType = () => {
  dictionaryList({ configType: 'part_type', keyword: '' }).then((res) => {
    if (res.code == 0) {
      state.search.param.forEach((i: any) => {
        if (i.prop == 'partType') {
          i.options = res.data
          i.options.unshift({
            configValue: '全部',
            customizeFlag: 0,
            id: '',
            parentId: '0'
          })
        }
      })
    }
  })
}
getPartType()

const delRelevance = (row: any) => {
  ElMessageBox.confirm('确定删除此备件与设备的关联吗', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      removeRelevanceApi(row.id).then((res) => {
        if (res.code == 0) {
          ElMessage({
            type: 'success',
            message: '已删除'
          })
          getTableData()
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消'
      })
    })
}

const relevanceDialog = ref(false)
const relevanceForm = ref({
  id: '',
  name: ''
})
const relevancePart = () => {
  // if (deviceId.value == '') {
  //   ElMessage.warning('请选择设备类型')
  // } else {
  relevanceForm.value.id = deviceId.value
  relevanceForm.value.name = deviceName.value
  relevanceDialog.value = !relevanceDialog.value
  // }
}

const relevance = () => {
  relevanceDialog.value = !relevanceDialog.value
}

const relevanceSubmit = () => {
  getTableData()
  relevanceDialog.value = !relevanceDialog.value
}

//定义方法对象 注意定义的方法 必须在上面已经申明 所以建议objFun申明和 listenClick方法 写在页面最下面
const objFun = {
  delRelevance: delRelevance,
  relevancePart: relevancePart
}
// 监听子级表格  传过来的方法
const listenClick = (name: string, val: any) => {
  objFun[name](val)
}

onMounted(() => {
  menu.forEach(async (element: any) => {
    if (element.menuUrl == '/assets/spareparts') {
      let res = await getButtonListByRoleApi({
        terminalType: 1,
        menuPid: element.id
      })
      res.data.forEach((item: any) => {
        buttonCodes.value.push(item.buttonCode)
      })
    }
  })
})
</script>
<style scoped lang="scss">
.sparePart {
  display: flex;

  &__tree {
    width: 15%;

    .title {
      // background-color: var(--el-color-primary);
      line-height: 40px;
      font-size: var(--el-font-size-base);
      font-weight: 500;
      padding: 0 10px;
      // margin-bottom: 5px;
    }
  }

  &__table {
    width: 85%;
    padding: 0 10px;
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: var(--el-font-size-base);
  padding-right: 8px;

  .treeLabel {
    width: 180px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.show-hide :nth-child(2) {
  display: none;
}

.show-hide:hover :nth-child(2) {
  display: inline-block !important;
}

.active {
  color: var(--el-color-primary);
}
</style>
<style>
.el-button--warning.is-plain {
  --el-button-bg-color: #fdf6ec;
  --el-button-hover-text-color: #e6a23c;
  --el-button-hover-bg-color: #fdf6ec;
}

.el-button--warning.is-plain:hover {
  --el-button-hover-text-color: #fff;
  --el-button-hover-bg-color: #e6a23c;
}

.el-button--danger.is-plain {
  --el-button-bg-color: #fef0f0;
  --el-button-hover-text-color: #f56c6c;
  --el-button-hover-bg-color: #fef0f0;
}

.el-button--danger.is-plain:hover {
  --el-button-hover-text-color: #fff;
  --el-button-hover-bg-color: #f56c6c;
}
</style>
